package entity

import (
	"time"

	"github.com/google/uuid"
)

// ClientMessageStatus 客户端消息状态
type ClientMessageStatus string

const (
	ClientMessageStatusPending   ClientMessageStatus = "pending"   // 处理中
	ClientMessageStatusCompleted ClientMessageStatus = "completed" // 已完成
	ClientMessageStatusFailed    ClientMessageStatus = "failed"    // 失败
)

// ClientMessage 面向客户端的消息表，用于前端展示
// 每条消息代表一个独立的消息（用户消息或助手消息）
type ClientMessage struct {
	ID             uuid.UUID `gorm:"primaryKey;type:uuid;column:id;default:uuid_generate_v4()"`
	ConversationID uuid.UUID `gorm:"type:uuid;column:conversation_id;not null;index"`
	UserID         uuid.UUID `gorm:"column:user_id;index"` // 用户ID
	CreatedAt      time.Time `gorm:"column:created_at;autoCreateTime"`
	UpdatedAt      time.Time `gorm:"column:updated_at;autoUpdateTime"`

	// 消息基本信息
	Role             string `gorm:"column:role;not null"`     // "user" 或 "assistant"
	Content          string `gorm:"column:content;not null"`  // 消息内容
	ReasoningContent string `gorm:"column:reasoning_content"` // AI推理过程内容

	// 状态信息（主要用于assistant消息）
	Status ClientMessageStatus `gorm:"column:status;default:'completed'"`

	// 元数据（主要用于assistant消息）
	ProcessingTime int64  `gorm:"column:processing_time"` // 处理时长(毫秒)
	Model          string `gorm:"column:model"`           // 使用的模型
	TokensUsed     int    `gorm:"column:tokens_used"`     // 消耗的token数

	// 错误信息
	ErrorMessage string `gorm:"column:error_message"` // 错误信息

	// 对话轮次ID，用于关联一轮完整对话的所有相关消息
	// 主要用于：
	// 1. 关联同一轮对话的user消息和assistant消息
	// 2. 关联这轮对话产生的所有LLM交互消息
	// 3. 支持重新生成回复功能
	// 4. 便于消息分析和调试
	// 注意：这是必填字段，每次对话都必须有对话轮次ID
	ConversationRoundID uuid.UUID `gorm:"type:uuid;column:conversation_round_id;not null;index"`

	// 关联
	User         *User         `gorm:"foreignKey:UserID"`
	Conversation *Conversation `gorm:"foreignKey:ConversationID"`
}

// TableName 指定表名
func (ClientMessage) TableName() string {
	return "client_messages"
}

// IsCompleted 检查消息是否已完成处理
func (cm *ClientMessage) IsCompleted() bool {
	return cm.Status == ClientMessageStatusCompleted
}

// IsFailed 检查消息是否处理失败
func (cm *ClientMessage) IsFailed() bool {
	return cm.Status == ClientMessageStatusFailed
}

// SetCompleted 标记assistant消息为已完成
func (cm *ClientMessage) SetCompleted(processingTime int64, tokensUsed int, model string) {
	cm.Status = ClientMessageStatusCompleted
	cm.ProcessingTime = processingTime
	cm.TokensUsed = tokensUsed
	cm.Model = model
	cm.ErrorMessage = ""
}

// IsUserMessage 检查是否为用户消息
func (cm *ClientMessage) IsUserMessage() bool {
	return cm.Role == "user"
}

// IsAssistantMessage 检查是否为助手消息
func (cm *ClientMessage) IsAssistantMessage() bool {
	return cm.Role == "assistant"
}

// SetFailed 标记消息为失败
func (cm *ClientMessage) SetFailed(errorMsg string) {
	cm.Status = ClientMessageStatusFailed
	cm.ErrorMessage = errorMsg
}

// SetConversationRound 设置对话轮次ID，用于关联一轮完整对话的所有相关消息
func (cm *ClientMessage) SetConversationRound(roundID uuid.UUID) {
	cm.ConversationRoundID = roundID
}

// GetConversationRoundID 获取对话轮次ID
func (cm *ClientMessage) GetConversationRoundID() uuid.UUID {
	return cm.ConversationRoundID
}

// GenerateNewConversationRoundID 生成新的对话轮次ID并设置到消息中
func (cm *ClientMessage) GenerateNewConversationRoundID() uuid.UUID {
	roundID := uuid.New()
	cm.ConversationRoundID = roundID
	return roundID
}
